<template>
  <div class="appointment-form-container">
    <div class="page-header">
      <h2>预约信息填写</h2>
      <p>填写您的上门服务预约需求，为您提供专业的定制咨询服务</p>
    </div>
    
    <el-card class="form-card">
      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="填写基本信息" />
        <el-step title="选择服务时间" />
        <el-step title="确认提交" />
      </el-steps>
      
      <div class="step-content">
        <!-- 步骤1：基本信息 -->
        <div v-if="currentStep === 1" class="step-form">
          <el-form 
            ref="basicInfoFormRef"
            :model="basicInfoForm" 
            :rules="basicInfoRules" 
            label-position="top"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人姓名" prop="contactName">
                  <el-input v-model="basicInfoForm.contactName" placeholder="请输入联系人姓名" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="basicInfoForm.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="上门服务地址" prop="serviceAddress">
                  <el-input v-model="basicInfoForm.serviceAddress" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预约人数" prop="peopleCount">
                  <el-input-number v-model="basicInfoForm.peopleCount" :min="1" :max="50" style="width: 100%" />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="预约类型" prop="appointmentType">
                  <el-select v-model="basicInfoForm.appointmentType" placeholder="请选择预约类型" style="width: 100%">
                    <el-option label="团体定制咨询" value="group" />
                    <el-option label="个人定制咨询" value="individual" />
                    <el-option label="企业形象设计" value="corporate" />
                    <el-option label="其他服务" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="需求描述" prop="requirementDesc">
                  <el-input 
                    v-model="basicInfoForm.requirementDesc" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请详细描述您的需求，例如：服装类型、风格偏好、定制人群等"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <div class="step-actions">
            <el-button type="primary" @click="nextStep">下一步</el-button>
          </div>
        </div>
        
        <!-- 步骤2：选择时间 -->
        <div v-if="currentStep === 2" class="step-form">
          <el-alert
            title="请选择您希望的服务时间，我们会根据设计师可用情况为您安排"
            type="info"
            :closable="false"
            style="margin-bottom: 20px"
          />
          
          <el-form 
            ref="timeFormRef"
            :model="timeForm" 
            :rules="timeRules" 
            label-position="top"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="期望服务日期" prop="serviceDate">
                  <el-date-picker
                    v-model="timeForm.serviceDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="期望服务时间段" prop="serviceTime">
                  <el-select v-model="timeForm.serviceTime" placeholder="请选择时间段" style="width: 100%">
                    <el-option label="上午 (9:00-12:00)" value="morning" />
                    <el-option label="下午 (13:00-17:00)" value="afternoon" />
                    <el-option label="晚上 (18:00-21:00)" value="evening" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备选日期与时间" prop="alternativeTime">
                  <el-space direction="vertical" style="width: 100%">
                    <div
                      v-for="(item, index) in timeForm.alternativeTimes"
                      :key="index"
                      class="alternative-time-item"
                    >
                      <el-row :gutter="10">
                        <el-col :span="10">
                          <el-date-picker
                            v-model="item.date"
                            type="date"
                            placeholder="选择备选日期"
                            style="width: 100%"
                            :disabled-date="disabledDate"
                          />
                        </el-col>
                        <el-col :span="10">
                          <el-select v-model="item.time" placeholder="请选择时间段" style="width: 100%">
                            <el-option label="上午 (9:00-12:00)" value="morning" />
                            <el-option label="下午 (13:00-17:00)" value="afternoon" />
                            <el-option label="晚上 (18:00-21:00)" value="evening" />
                          </el-select>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center">
                          <el-button
                            type="danger"
                            circle
                            @click="removeAlternativeTime(index)"
                            v-if="timeForm.alternativeTimes.length > 1"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </el-col>
                      </el-row>
                    </div>
                    
                    <el-button
                      type="primary"
                      plain
                      @click="addAlternativeTime"
                      :disabled="timeForm.alternativeTimes.length >= 3"
                    >
                      <el-icon><Plus /></el-icon>
                      添加备选时间
                    </el-button>
                  </el-space>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="预计服务时长" prop="serviceDuration">
                  <el-select v-model="timeForm.serviceDuration" placeholder="请选择预计服务时长" style="width: 100%">
                    <el-option label="1小时以内" value="1hour" />
                    <el-option label="1-2小时" value="2hours" />
                    <el-option label="2-3小时" value="3hours" />
                    <el-option label="3小时以上" value="3hours+" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="其他时间安排要求" prop="timeRequirements">
                  <el-input 
                    v-model="timeForm.timeRequirements" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="如有其他关于时间的特殊要求，请在此说明"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="nextStep">下一步</el-button>
          </div>
        </div>
        
        <!-- 步骤3：确认信息 -->
        <div v-if="currentStep === 3" class="step-form">
          <h3 class="confirm-title">请确认您的预约信息</h3>
          
          <el-descriptions title="基本信息" :column="1" border>
            <el-descriptions-item label="联系人姓名">{{ basicInfoForm.contactName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ basicInfoForm.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="上门服务地址">{{ basicInfoForm.serviceAddress }}</el-descriptions-item>
            <el-descriptions-item label="预约人数">{{ basicInfoForm.peopleCount }}人</el-descriptions-item>
            <el-descriptions-item label="预约类型">{{ getAppointmentTypeText(basicInfoForm.appointmentType) }}</el-descriptions-item>
            <el-descriptions-item label="需求描述">{{ basicInfoForm.requirementDesc || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <el-descriptions title="时间安排" :column="1" border style="margin-top: 20px">
            <el-descriptions-item label="期望服务日期">{{ formatDate(timeForm.serviceDate) }}</el-descriptions-item>
            <el-descriptions-item label="期望服务时间段">{{ getTimeRangeText(timeForm.serviceTime) }}</el-descriptions-item>
            <el-descriptions-item label="备选时间">
              <div v-for="(item, index) in timeForm.alternativeTimes" :key="index" style="margin-bottom: 5px">
                备选{{ index + 1 }}：{{ formatDate(item.date) }} {{ getTimeRangeText(item.time) }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="预计服务时长">{{ getServiceDurationText(timeForm.serviceDuration) }}</el-descriptions-item>
            <el-descriptions-item label="其他时间要求">{{ timeForm.timeRequirements || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider />
          
          <div class="agreement">
            <el-checkbox v-model="agreement">我已阅读并同意<el-button type="primary" link @click="showAgreement">《上门服务协议》</el-button></el-checkbox>
          </div>
          
          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="submitAppointment" :disabled="!agreement">提交预约</el-button>
          </div>
        </div>
        
        <!-- 提交成功 -->
        <div v-if="currentStep === 4" class="success-info">
          <el-result
            icon="success"
            title="预约提交成功"
            sub-title="我们会尽快安排设计师与您联系，确认预约详情"
          >
            <template #extra>
              <el-button type="primary" @click="goToDesignerSelection">立即前往选择设计师</el-button>
              <el-button @click="resetForm">再次预约</el-button>
            </template>
            
            <div class="result-info">
              <p><strong>预约编号：</strong>{{ appointmentNo }}</p>
              <p><strong>提交时间：</strong>{{ submissionTime }}</p>
              <p>您可以在"上门服务预约 > 设计师选择"页面中查看可选设计师及其评价，根据需求选择合适的设计师提供服务。</p>
            </div>
          </el-result>
        </div>
      </div>
    </el-card>
    
    <!-- 服务协议对话框 -->
    <el-dialog v-model="agreementDialogVisible" title="上门服务协议" width="50%">
      <div class="agreement-content">
        <h4>服装定制上门服务协议</h4>
        <p>欢迎使用我们的上门量体和定制咨询服务，请您在预约服务前仔细阅读本协议的所有条款。</p>
        
        <h5>1. 服务内容</h5>
        <p>我们的上门服务包括但不限于：专业量体、面料展示、款式咨询、定制方案制定等服务。</p>
        
        <h5>2. 服务约定</h5>
        <p>
          2.1 预约成功后，我们会根据您选择的时间安排设计师上门服务。<br>
          2.2 如需取消或更改预约，请至少提前24小时通知我们。<br>
          2.3 上门服务过程中，请保证提供的地址准确无误，并确保安全的服务环境。
        </p>
        
        <h5>3. 收费标准</h5>
        <p>
          3.1 上门量体服务本身是免费的，但需要您在服务结束后提供交通费用报销。<br>
          3.2 如您选择的上门地点超出服务范围，可能需要额外收取交通费用，具体费用将提前与您沟通确认。<br>
          3.3 如预约后客户方原因取消预约且未提前24小时通知，我们保留收取相应违约金的权利。
        </p>
        
        <h5>4. 隐私保护</h5>
        <p>
          4.1 我们会严格保护您的个人信息和量体数据。<br>
          4.2 未经您的许可，我们不会将您的个人信息用于与本次服务无关的其他用途。
        </p>
        
        <h5>5. 争议解决</h5>
        <p>
          本协议的签订、效力、解释、履行和争议解决均适用中华人民共和国法律。因本协议引起的或与本协议有关的任何争议，双方应友好协商解决；协商不成的，任何一方均有权向服务提供方所在地人民法院提起诉讼。
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="agreementDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="agreeToTerms">同意协议</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'

export default {
  name: 'AppointmentForm',
  components: {
    Delete,
    Plus
  },
  setup() {
    const router = useRouter()
    
    // 当前步骤
    const currentStep = ref(1)
    
    // 基本信息表单
    const basicInfoFormRef = ref(null)
    const basicInfoForm = reactive({
      contactName: '',
      contactPhone: '',
      serviceAddress: '',
      peopleCount: 1,
      appointmentType: '',
      requirementDesc: ''
    })
    
    const basicInfoRules = {
      contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      serviceAddress: [
        { required: true, message: '请输入上门服务地址', trigger: 'blur' }
      ],
      appointmentType: [
        { required: true, message: '请选择预约类型', trigger: 'change' }
      ]
    }
    
    // 时间选择表单
    const timeFormRef = ref(null)
    const timeForm = reactive({
      serviceDate: '',
      serviceTime: '',
      alternativeTimes: [
        { date: '', time: '' }
      ],
      serviceDuration: '',
      timeRequirements: ''
    })
    
    const timeRules = {
      serviceDate: [
        { required: true, message: '请选择期望服务日期', trigger: 'change' }
      ],
      serviceTime: [
        { required: true, message: '请选择期望服务时间段', trigger: 'change' }
      ],
      serviceDuration: [
        { required: true, message: '请选择预计服务时长', trigger: 'change' }
      ]
    }
    
    // 禁用今天之前的日期
    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
    }
    
    // 添加备选时间
    const addAlternativeTime = () => {
      if (timeForm.alternativeTimes.length < 3) {
        timeForm.alternativeTimes.push({ date: '', time: '' })
      }
    }
    
    // 移除备选时间
    const removeAlternativeTime = (index) => {
      timeForm.alternativeTimes.splice(index, 1)
    }
    
    // 获取预约类型文本
    const getAppointmentTypeText = (type) => {
      const typeMap = {
        'group': '团体定制咨询',
        'individual': '个人定制咨询',
        'corporate': '企业形象设计',
        'other': '其他服务'
      }
      return typeMap[type] || type
    }
    
    // 获取时间段文本
    const getTimeRangeText = (time) => {
      const timeMap = {
        'morning': '上午 (9:00-12:00)',
        'afternoon': '下午 (13:00-17:00)',
        'evening': '晚上 (18:00-21:00)'
      }
      return timeMap[time] || time
    }
    
    // 获取服务时长文本
    const getServiceDurationText = (duration) => {
      const durationMap = {
        '1hour': '1小时以内',
        '2hours': '1-2小时',
        '3hours': '2-3小时',
        '3hours+': '3小时以上'
      }
      return durationMap[duration] || duration
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      
      return `${year}-${month}-${day}`
    }
    
    // 下一步
    const nextStep = async () => {
      if (currentStep.value === 1) {
        const valid = await basicInfoFormRef.value.validate().catch(() => false)
        if (!valid) {
          ElMessage.error('请填写完整的基本信息')
          return
        }
      } else if (currentStep.value === 2) {
        const valid = await timeFormRef.value.validate().catch(() => false)
        if (!valid) {
          ElMessage.error('请填写完整的时间信息')
          return
        }
      }
      
      currentStep.value++
    }
    
    // 上一步
    const prevStep = () => {
      if (currentStep.value > 1) {
        currentStep.value--
      }
    }
    
    // 服务协议
    const agreementDialogVisible = ref(false)
    const agreement = ref(false)
    
    const showAgreement = () => {
      agreementDialogVisible.value = true
    }
    
    const agreeToTerms = () => {
      agreement.value = true
      agreementDialogVisible.value = false
    }
    
    // 提交预约
    const appointmentNo = ref('')
    const submissionTime = ref('')
    
    const submitAppointment = () => {
      if (!agreement.value) {
        ElMessage.warning('请阅读并同意上门服务协议')
        return
      }
      
      // 生成预约编号
      const now = new Date()
      const timestamp = now.getTime()
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      appointmentNo.value = `A${timestamp}${randomNum}`
      
      // 格式化提交时间
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      submissionTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      
      // 这里应该调用API提交预约信息
      ElMessage.success('预约信息提交成功')
      
      // 显示成功页面
      currentStep.value = 4
    }
    
    // 重置表单
    const resetForm = () => {
      basicInfoFormRef.value.resetFields()
      timeFormRef.value.resetFields()
      timeForm.alternativeTimes = [{ date: '', time: '' }]
      agreement.value = false
      currentStep.value = 1
    }
    
    // 前往设计师选择
    const goToDesignerSelection = () => {
      router.push('/appointment/designer')
    }
    
    // 初始化
    onMounted(() => {
      // 从用户信息中获取联系人姓名和电话
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          const parsedUserInfo = JSON.parse(userInfo)
          if (parsedUserInfo.name) {
            basicInfoForm.contactName = parsedUserInfo.name
          }
          if (parsedUserInfo.phone) {
            basicInfoForm.contactPhone = parsedUserInfo.phone
          }
        } catch (e) {
          console.error('Parse user info error:', e)
        }
      }
      
      // 从企业信息中获取地址
      const enterpriseInfo = localStorage.getItem('enterpriseInfo')
      if (enterpriseInfo) {
        try {
          const parsedEnterpriseInfo = JSON.parse(enterpriseInfo)
          if (parsedEnterpriseInfo.address) {
            basicInfoForm.serviceAddress = parsedEnterpriseInfo.address
          }
        } catch (e) {
          console.error('Parse enterprise info error:', e)
        }
      }
    })
    
    return {
      currentStep,
      basicInfoFormRef,
      basicInfoForm,
      basicInfoRules,
      timeFormRef,
      timeForm,
      timeRules,
      disabledDate,
      addAlternativeTime,
      removeAlternativeTime,
      getAppointmentTypeText,
      getTimeRangeText,
      getServiceDurationText,
      formatDate,
      nextStep,
      prevStep,
      agreementDialogVisible,
      agreement,
      showAgreement,
      agreeToTerms,
      appointmentNo,
      submissionTime,
      submitAppointment,
      resetForm,
      goToDesignerSelection
    }
  }
}
</script>

<style scoped>
.appointment-form-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.form-card {
  margin-bottom: 24px;
}

.step-content {
  margin-top: 30px;
}

.step-form {
  max-width: 800px;
  margin: 0 auto;
}

.step-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.alternative-time-item {
  margin-bottom: 10px;
}

.confirm-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  text-align: center;
}

.agreement {
  margin: 20px 0;
  text-align: center;
}

.success-info {
  padding: 20px 0;
}

.result-info {
  text-align: left;
  margin-top: 20px;
  padding: 20px;
  background: #f7f7f7;
  border-radius: 4px;
}

.agreement-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.agreement-content h4 {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-content h5 {
  margin-top: 15px;
  margin-bottom: 10px;
}

.agreement-content p {
  margin-bottom: 15px;
  line-height: 1.6;
}
</style> 